<?php

namespace app\admin\controller\dahuis;

use app\admin\model\AuthGroupAccess;
use app\common\controller\Backend;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\Db;
use think\Exception;

/**
 * 社保公积金订单管理
 *
 * @icon fa fa-circle-o
 */
class Sbgjj extends Backend
{
    
    /**
     * Sbgjj模型对象
     * @var \app\admin\model\dahuis\Sbgjj
     */
    protected $model = null;
    protected $noNeedRight = ["yjxf", "havesamejnr"];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\dahuis\Sbgjj;
        $this->view->assign("isxyList", $this->model->getIsxyList());

    }

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $u = AuthGroupAccess::where('uid', $this->auth->id)->find();
            if ($u->group_id == 15) {
                $total = $this->model
                    ->with(['admin'])
                    ->where($where)
                    ->where('admin_id', $this->auth->id)
                    ->order($sort, $order)
                    ->count();

                $list = $this->model
                    ->with(['admin'])
                    ->where($where)
                    ->where('admin_id', $this->auth->id)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            } else {
                $total = $this->model
                    ->with(['admin'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

                $list = $this->model
                    ->with(['admin'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            }

            $list = collection($list)->toArray();
            $filter = $this->request->get("filter", '');
            $filter = (array)json_decode($filter, true);
            if (isset($filter['htstart'])) {
                $sql = "select sum(htje) as num from fa_dahuis_sbgjj where htstart = '{$filter['htstart']}' ";
                $money = Db::query($sql);
                $result = array("total" => $total, "rows" => $list, "extend" => ['money' => sprintf("%.2f", $money[0]['num'])]);
            } else {
                $result = array("total" => $total, "rows" => $list, "extend" => ['money' => ""]);
            }

            return json($result);
        }
        return $this->view->fetch();
    }




    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }

                    if (isset($params['htstart']) && isset($params['htend'])) {
                        $params['htstart'] = trim($params['htstart']);
                        $params['htend'] = trim($params['htend']);
                        $params['htend2'] = $params['htend'];
                    }

                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                    
                    //先删除原关联的记录
                    if (isset($params['htstart']) && isset($params['htend']) && strlen($params['htstart']) > 0 && $params['htend'] >= $params['htstart']) {

                        $from = $params['htstart'];
                        $to = $params['htend'];
                        $newny = $from;
                        for ($i = 0; $i < 48; $i++) {
                            $ny = \app\admin\model\dahuis\Sbgjjmonth::where("sbgjj_id", $this->model->id)->where("sbyf", $newny)->find();
                            if (!$ny) {
                                $ny = new \app\admin\model\dahuis\Sbgjjmonth;
                                $ny->sbgjj_id = $this->model->id;
                                $ny->sbyf = $newny;
                            }
                            $ny->zczt = "未办理";
                            $ny->save();

                            $newny = date("Y-m", strtotime("+1 months", strtotime($newny)));
                            if ($newny > $to) {
                                break;
                            }
                        }
                    }

                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $sbbl = 0;
        $gjjbl = 0;
        $b = \app\admin\model\dahuis\Base::get(1);
        if ($b) {
            $sbbl = $b->sbbl;
            $gjjbl = $b->gjjbl;
        }
        $this->view->assign("sbbl", $sbbl);
        $this->view->assign("gjjbl", $gjjbl);
        return $this->view->fetch();
    }

    /**
     * 一键续费
     */
    public function yjxf($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }

                    if (isset($params['htstart']) && isset($params['htend'])) {
                        $params['htstart'] = trim($params['htstart']);
                        $params['htend'] = trim($params['htend']);
                        $params['htend2'] = $params['htend'];
                    }

                    $row->isxy = "已续约";
                    $row->save();
                    
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();

                    //先删除原关联的记录
                    if (isset($params['htstart']) && isset($params['htend']) && strlen($params['htstart']) > 0 && $params['htend'] >= $params['htstart']) {

                        $from = $params['htstart'];
                        $to = $params['htend'];
                        $newny = $from;
                        for ($i = 0; $i < 48; $i++) {
                            $ny = \app\admin\model\dahuis\Sbgjjmonth::where("sbgjj_id", $this->model->id)->where("sbyf", $newny)->find();
                            if (!$ny) {
                                $ny = new \app\admin\model\dahuis\Sbgjjmonth;
                                $ny->zczt = "未办理";
                            }
                            $ny->sbgjj_id = $this->model->id;
                            $ny->sbyf = $newny;
                            $ny->save();

                            $newny = date("Y-m", strtotime("+1 months", strtotime($newny)));
                            if ($newny > $to) {
                                break;
                            }
                        }
                    }

                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $row->htstart = date("Y-m", strtotime("+1 months", strtotime($row->htend)));
        $row->htend = date("Y-m", strtotime("+11 months", strtotime($row->htstart)));
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    if ($this->auth->id != 38 && $this->auth->id != 1) {
                        $xtime = time() - strtotime($v->create_time);
                        if ($xtime > 15 * 86400) {
                            $this->error(__('不能删除已超时'));
                        }
                    }

                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }


    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }

//                    if ($this->auth->id != 38 && $this->auth->id != 1) {
//                        $xtime = time() - strtotime($row->create_time);
//                        if ($xtime > 15 * 86400) {
//                            $this->error(__('不能修改已超时'));
//                        }
//                    }

                    if (isset($params['htstart']) && isset($params['htend'])) {
                        $params['htstart'] = trim($params['htstart']);
                        $params['htend'] = trim($params['htend']);
                        $params['htend2'] = $params['htend'];
                    }

                    $htstart = $row->htstart;
                    $htend = $row->htend;
                    $result = $row->allowField(true)->save($params);
                    Db::commit();

                    //修改合同日期后
                    if (isset($params['htstart']) && isset($params['htend']) && strlen($params['htstart']) > 0 && $params['htend'] >= $params['htstart']) {
                        $from = $params['htstart'];
                        $to = $params['htend'];
                        $newny = $from;
                        for ($i = 0; $i < 48; $i++) {
                            $ny = \app\admin\model\dahuis\Sbgjjmonth::where("sbgjj_id", $row->id)->where("sbyf", $newny)->find();
                            if (!$ny) {
                                $ny = new \app\admin\model\dahuis\Sbgjjmonth;
                                $ny->sbyf = $newny;
                                $ny->zczt = "未办理";
                            }
                            $ny->sbgjj_id = $row->id;
                            $ny->save();

                            $newny = date("Y-m", strtotime("+1 months", strtotime($newny)));
                            if ($newny > $to) {
                                break;
                            }
                        }
                    }

                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);

        $sbbl = 0;
        $gjjbl = 0;
        $b = \app\admin\model\dahuis\Base::get(1);
        if ($b) {
            $sbbl = $b->sbbl;
            $gjjbl = $b->gjjbl;
        }
        $this->view->assign("sbbl", $sbbl);
        $this->view->assign("gjjbl", $gjjbl);

        return $this->view->fetch();
    }


    //http://dahui.test/admin/dahuis/sbgjj/havesamejnr?idc=341221199803066322
    //本月同一个缴纳人已有订单
    public function havesamejnr()
    {
        $idc = $this->request->request('idc');
        if (!$idc) {
            $this->success('空的身份证！');
        }

        $data = \app\admin\model\dahuis\Sbgjj::where("htstart", date("Y-m"))->where("idc", $idc)->find();
        if ($data) {
            $this->error('本月此身份证已有重复订单！');
        }

        $this->success('本月无重复记录', null, null);
    }


}
